package cool.taomu.toolkit.markdown

import java.io.StringWriter
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory
import java.io.File
import java.util.Arrays
import org.commonmark.ext.gfm.tables.TablesExtension
import org.commonmark.parser.Parser
import org.commonmark.renderer.html.HtmlRenderer
import java.io.InputStreamReader
import java.io.FileInputStream
import cool.taomu.toolkit.template.ITemplate
import java.util.Map

class MarkdownUtils implements ITemplate{
	val static LOG = LoggerFactory.getLogger(MarkdownUtils);

	def String getHtml(String path) {
		LOG.info("生成Markdown文档")
		var file = new File(path);
		if (file.exists) {
			return getHtml(file);
		}
		return "";
	}

	def String getHtml(File file) {
		var extensions = Arrays.asList(TablesExtension.create());
		var Parser parser = Parser.builder().extensions(extensions).build();
		var HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
		var document = parser.parseReader(new InputStreamReader(new FileInputStream(file)));
		return renderer.render(document);
	}
	
	override execute(String path, Map<String, Object> dataModel) {
		var StringWriter writer = new StringWriter();
		try {
			writer.append(getHtml(path));
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		}
		return writer
	}

}
